package com.cmw.auntapp.ui;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import butterknife.ButterKnife;

import com.cmw.auntapp.R;
import com.cmw.auntapp.component.TitleBar;
import com.cmw.auntapp.constant.CommandType;
import com.cmw.auntapp.constant.Constant;
import com.cmw.auntapp.core.base.IBaseView;
import com.cmw.auntapp.core.base.IPresenter;
import com.cmw.auntapp.core.base.vo.DataResult;
import com.cmw.auntapp.core.util.MyActivityManager;
import com.cmw.auntapp.core.util.SharedPreferencesUtil;
import com.cmw.auntapp.core.util.ToastAlert;
import com.cmw.auntapp.listener.BackListener;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.cmw.auntapp.constant.CommandType.NONE;
import static com.cmw.auntapp.constant.Constant.IS_GOTO_LOGIN_KEY;
import static com.xiasuhuei321.loadingdialog.view.LoadingDialog.Speed.SPEED_ONE;


public abstract class BaseActivity extends AppCompatActivity implements IBaseView {

    protected static String TAG = "BaseActivity";

    private TitleBar titleBar;

    protected LoadingDialog ld;

    private ProgressDialog progressDialog;

    private boolean isSysLoading = true; // 默认使用系统Loading

    protected List<LoadingDialog> loadingDialogList = new ArrayList<>();

    /**
     * 记录跳转到实名或登录前的上一个Activity所要去到的目标Activity
     * 此处记录好处是：当做完了登录和实名后能自动返回原始页面
     */
    private static Class prevTargetActivity = null;
    /**
     * 记录跳转到实名或登录前的上一个Activity 所要去到的目标Activity 所需参数
     * 此处记录好处是：当做完了登录和实名后能自动返回原始页面
     */
    private static Map<String,String> prevParams = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        TAG = this.getClass().getSimpleName();
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // 设为只竖屏显示
        int layoutResourceId = getActivityLayout();
        if (layoutResourceId > 0) {
            setContentView(layoutResourceId);
        }
        ButterKnife.bind(this);
        //createLoading();
        ToastAlert.init(this);
        if (isSysLoading) {
            buildProgressDialog();
        }
        onInit(savedInstanceState);
    }

    private void buildProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setMessage(getString(R.string.common_loading_msg));
            progressDialog.setCancelable(true);
        }
    }

    private LoadingDialog createLoading() {
        LoadingDialog loadingDialog = new LoadingDialog(this);
        loadingDialog.setLoadingText("加载中")
                .setSuccessText("加载成功")
                .setLoadSpeed(SPEED_ONE)
                .closeSuccessAnim();
        return loadingDialog;
    }

    protected int getActivityLayout() {
        return 0;
    }

    protected boolean doSuccess(CommandType commandType, DataResult dataResult) {
        return false;
    }

    protected boolean doFailure(CommandType commandType, DataResult dataResult) {
        return false;
    }

    protected IPresenter getPresenter(){
        return null;
    }

    private void initTitleBar() {
       if (titleBar == null) {
           titleBar = findViewById(R.id.title_bar);
       }
    }

    public void setTitle(int resId){
        int activityCount = getActivityCount();
        boolean showBackButton = false;
        if (activityCount > 1) {
            showBackButton = true;
        }
        setTitle(resId, showBackButton);
    }

    /**
     * 获取自定义页面Title返回事件
     * @return  返回BackListener 对象
     */
    protected BackListener getCustBackListener() {
        return null;
    }

    protected void setTitle(int resId, boolean showBack){
        initTitleBar();
        titleBar.setTitle(resId);
        titleBar.isShowBack(showBack);
        BackListener backListener = getCustBackListener();
        if (null != backListener) {
            titleBar.setBackListener(backListener);
        }
    }

    /**
     * 显示标题栏
     */
    protected void hideTitleBar(){
        titleBar.setVisibility(View.GONE);
    }

    /**
     * 隐藏标题栏
     */
    protected void showTitleBar(){
        titleBar.setVisibility(View.VISIBLE);
    }

    /**
     * 获取 Activity数量
     * @return
     */
    protected int getActivityCount() {
        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> taskInfoList =am.getRunningTasks(10);//
       // 这里获取的是APP栈的数量，一般也就两个
        ActivityManager.RunningTaskInfo runningTaskInfo = taskInfoList.get(0);// 只是拿          当前运行的栈
        int numActivities = taskInfoList.get(0).numActivities;
        return numActivities;
    }

    protected void gotoBack() {
        finish();
    }

    protected <T> void gotoBack(Class<T> defaultActivityCls) {
        if (getActivityCount() > 1 || null == defaultActivityCls){
            finish();
        } else{
            Intent intent = new Intent(this, defaultActivityCls);
            startActivity(intent);
        }
    }

    protected <T> void go() {
        go(null, null, NONE);
    }

    protected <T> void go(Class<T> defaultActivityCls) {
        go(defaultActivityCls, null, NONE);
    }

    protected <T> void go(Class defaultActivityCls, Map<String,String> params) {
        go(defaultActivityCls, params, NONE);
    }
    protected <T> void go(Class defaultActivityCls, Map<String,String> params, CommandType commandType) {
        Intent intent = new Intent();
        switch (commandType) {
            case CHECK_REAL_NAME:{
                cachePrevTargetActivityInfo(defaultActivityCls, params);
                defaultActivityCls = UserEditActivity.class;
                break;
            }case CHECK_LOGIN:{
                cachePrevTargetActivityInfo(defaultActivityCls, params);
                defaultActivityCls = LoginActivity.class;
            } default:{
                if (null != prevTargetActivity) { //跳转到上次的目标Activity
                    defaultActivityCls = prevTargetActivity;
                    params = prevParams;
                }
            }
        }
        putParams(intent, params);
        intent.setClass(this, defaultActivityCls);
        startActivity(intent);
        clearPrevTargetActivityInfo();
    }

    protected void putParams(Intent intent, Map<String, String> params){
        if (null == params || params.isEmpty()) {
            return;
        }
        Bundle bundle = new Bundle();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            params.entrySet().forEach(entry -> {
                bundle.putString(entry.getKey(), entry.getValue());
            });
        }
        intent.putExtras(bundle);
    }

    private void cachePrevTargetActivityInfo(Class defaultActivityCls, Map<String,String> params) {
        prevTargetActivity = defaultActivityCls;
        prevParams = params;
    }

    private void clearPrevTargetActivityInfo(){
        prevTargetActivity = null;
        prevParams = null;
    }

    @Override
    public void loading() {
        if (isSysLoading && !progressDialog.isShowing()) {
            progressDialog.show();
            return;
        }
        LoadingDialog loadingDialog = createLoading();
        loadingDialogList.add(loadingDialog);
        loadingDialog.show();
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void hideLoading() {
        if (isSysLoading && progressDialog.isShowing()) {
            progressDialog.cancel();
            return;
        }

        if (null == loadingDialogList || loadingDialogList.size() == 0) {
            return;
        }
        runOnUiThread(() -> {
            loadingDialogList.forEach(ld -> {
                if (ld == null) {
                    return;
                }
                ld.close();
            });
            loadingDialogList.clear();
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public boolean success(CommandType commandType, DataResult dataResult) {
        runOnUiThread(()->{
            this.hideLoading();
            doSuccess(commandType, dataResult);
        });
        return true;
    }

    private static boolean isGoToLogin = false; // 防止两次跳转到登录页面

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public boolean failure(CommandType commandType, DataResult dataResult) {
        runOnUiThread(()->{
            this.hideLoading();
            switch (commandType) {
                case LOCAL_ERR:{
                    Toast.makeText(this, dataResult.getMsg(), Toast.LENGTH_SHORT).show();
                    break;
                }case AUTH_FAIL:{
                    Activity currentActivity = MyActivityManager.getInstance().getCurrentActivity();
                    if (currentActivity instanceof LoginActivity) {
                        return;
                    }
                    if (Constant.isGoLogin) { // 如果已经去到了登录页，则返回
                        return;
                    }
                    synchronized (this) {
                        Toast.makeText(this, dataResult.getMsg(), Toast.LENGTH_SHORT).show();
                        doFailure(commandType, dataResult);
                        Constant.isGoLogin = true;
                        go(LoginActivity.class);
                    }
                    break;
                } default:{
                    boolean result = doFailure(commandType, dataResult);//注：如果重写 doFailure 方法，须将返回值设为:true
                    if (!result) { // 如果用户未重写doFailure方法，则默认给出 Toast提示
                        Toast.makeText(this, dataResult.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        return true;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onDestroy() {
        if (isSysLoading && progressDialog != null) {
            progressDialog.dismiss();
        } else {
            loadingDialogList.forEach(loadingDialog -> loadingDialog.close());
        }
        super.onDestroy();
    }

    abstract void onInit(Bundle savedInstanceState);
}
